//
//  SubscribeListViewController.m
//  suRead
//
//  Created by lidi on 2018/11/29.
//  Copyright © 2018 bao. All rights reserved.
//

#import "SubscribeListViewController.h"
#import "ServiceNews.h"
#import "ServiceSubscribe.h"
#import "Masonry.h"
#import "MJRefresh.h"
#import "SubscribeListCell.h"
#import "UIViewController+HUD.h"
#import "M_Subscribe.h"
#import "SubscribeNewsListViewController.h"
#import "AccountManager.h"
#import "UIViewController+EmptyDataSet.h"

@interface SubscribeListViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)NSMutableArray *infoData;
@property (nonatomic,strong)UITableView *infoTableView;
@property (nonatomic,strong)NSURLSessionDataTask *requestHandle;
@property (nonatomic,assign)NSInteger currentPageIndex;
@end

@implementation SubscribeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self) weak_self = self;
    self.infoTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.infoTableView.backgroundColor = [UIColor whiteColor];
    self.infoTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.infoTableView.delegate = self;
    self.infoTableView.dataSource = self;
    self.infoTableView.tableFooterView = [UIView new];
    [self.view addSubview:self.infoTableView];
    [self.infoTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weak_self.view).insets(UIEdgeInsetsZero);
    }];
    
    [self.infoTableView registerNib:[UINib nibWithNibName:@"SubscribeListCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SubscribeListCell"];
    
    self.infoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weak_self refreshData];
    }];
    
    self.infoTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weak_self loadMore];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weak_self.infoTableView.mj_header beginRefreshing];
    });
}

- (void)refreshData
{
    [self emptyDataSetClearAllNotice];
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    [self.infoTableView.mj_footer resetNoMoreData];
    
    __weak typeof(self) weak_self = self;
    NSString *uid = [AccountManager sharedAccountManager].f_uid;
    if (![AccountManager sharedAccountManager].f_isLogined) {
        uid = @"";
    }
    [ServiceSubscribe doFetchServicePidList:self.pid userid:uid pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
        self.infoData = [NSMutableArray array];
        if (responseObject && [responseObject isKindOfClass:[NSArray class]]) {
            [self.infoData addObjectsFromArray:responseObject];
        }
        
        if (!responseObject || [responseObject count] == 0) {
            [weak_self emptyDataSetShowEmptyData:@"暂无数据"];
            weak_self.infoTableView.mj_footer = nil;
        }
        
        [weak_self.infoTableView.mj_header endRefreshing];
        [weak_self.infoTableView reloadData];
    } failure:^(NSString *message) {
        [weak_self.infoTableView.mj_header endRefreshing];
    }];
}

- (void)loadMore
{
    self.currentPageIndex ++;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;
    NSString *uid = [AccountManager sharedAccountManager].f_uid;
    if (![AccountManager sharedAccountManager].f_isLogined) {
        uid = @"";
    }
    [ServiceSubscribe doFetchServicePidList:self.pid userid:uid pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id responseObject, NSString *message) {
        if (responseObject && [responseObject isKindOfClass:[NSArray class]]) {
            [self.infoData addObjectsFromArray:responseObject];
            if ([responseObject count] <=0) {
                [weak_self.infoTableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [weak_self.infoTableView.mj_footer endRefreshing];
            }
        } else {
            [weak_self.infoTableView.mj_footer endRefreshing];
        }
        [weak_self.infoTableView reloadData];
    } failure:^(NSString *message) {
        [weak_self.infoTableView.mj_footer endRefreshing];
    }];
}

#pragma mark tableViewDatasouce Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.infoData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SubscribeListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubscribeListCell"];
    
    __weak typeof (self) weakSelf = self;
    [cell refresh:self.infoData[indexPath.row] handle:^(BOOL isSub) {
        
        if ([AccountManager sharedAccountManager].f_isLogined) {
            M_Subscribe *sub = weakSelf.infoData[indexPath.row];
            NSString *uid = [AccountManager sharedAccountManager].f_uid;
            if (isSub) {
                [ServiceSubscribe doServiceSubscribe:sub.f_wid userid:uid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                    [weakSelf showHUDText:message];
                    sub.f_is_subscribe = YES;
                    [weakSelf.infoTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                } failure:^(NSString * _Nonnull message) {
                    [weakSelf showHUDText:message];
                }];
            } else {
                [ServiceSubscribe doServiceUnsubscribe:sub.f_wid userid:uid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                    [weakSelf showHUDText:message];
                    sub.f_is_subscribe = NO;
                    [weakSelf.infoTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                } failure:^(NSString * _Nonnull message) {
                    [weakSelf showHUDText:message];
                }];
            }
        } else {
            //需要登录
            UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
            UIViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"LoginViewController"];
            controller.hidesBottomBarWhenPushed = YES;
            [self showViewController:controller sender:nil];
        }
        
    }];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SubscribeNewsListViewController *controller = [SubscribeNewsListViewController new];
    controller.sub = self.infoData[indexPath.row];
    [self showViewController:controller sender:nil];
}


@end
